<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">深化插件版本管理</div>
        <div class="flex">
          <el-button
            type="primary"
            @click="show_box = true"
            v-if="has_role_list[0].has_role"
            >新增</el-button
          >

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height: height_size == 2 ? '50px' : '',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="版本号"
          prop="version"
          key="版本号"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="包大小(M)"
          prop="packageSize"
          key="包大小"
          sortable
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column
          label="文件地址"
          prop="dllUrl"
          key="文件地址"
          sortable
          v-if="header_list[2].showTable"
        ></el-table-column>
        <el-table-column
          label="下载地址"
          prop="downloadUrl"
          key="下载地址"
          sortable
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column
          label="全量包"
          prop="fullDownloadUrl"
          key="全量包"
          sortable
          v-if="header_list[4].showTable"
        ></el-table-column>
        <el-table-column
          label="强制更新"
          key="强制更新"
          sortable
          prop="enforce"
          width="120px"
          v-if="header_list[5].showTable"
        >
          <template #default="scope: any">
            <div v-show="scope.row?.enforce == 1">是</div>
            <div v-show="scope.row?.enforce != 1">否</div>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          key="状态"
          sortable
          prop="status"
          width="120px"
          v-if="header_list[6].showTable"
        >
          <template #default="scope: any">
            <div v-show="scope.row?.status == 1" style="color: #3580eb">
              启用
            </div>
            <div v-show="scope.row?.status != 1">停用</div>
          </template></el-table-column
        >
        <el-table-column
          label="创建人"
          prop="createByName"
          key="创建人"
          sortable
          v-if="header_list[7].showTable"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          key="创建时间"
          sortable
          prop="createTime"
          width="180px"
          v-if="header_list[8].showTable"
        >
          <template #default="scope: any">
            <span>{{
              formatDate(parseInt(scope.row.createTime), 'yyyy-MM-dd hh:mm:ss')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="更新人"
          key="更新人"
          sortable
          prop="updateByName"
          v-if="header_list[9].showTable"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          key="更新时间"
          sortable
          prop="updateTime"
          v-if="header_list[10].showTable"
          width="180px"
        >
          <template #default="scope: any">
            <span v-show="scope.row?.updateTime">{{
              formatDate(parseInt(scope.row.updateTime), 'yyyy-MM-dd hh:mm:ss')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="更新内容"
          key="更新内容"
          sortable
          prop="content"
          v-if="header_list[11].showTable"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="180"
          v-if="has_role_list[1].has_role"
        >
          <template #default="scope: any">
            <el-button type="primary" @click="edit_list(scope.row)"
              >编辑</el-button
            >
            <!-- <el-button @click="delete_list(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    @close="resetForm(addversionform)"
    size="60%"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增深化插件版本</h4>
      <h4 v-else>编辑深化插件版本</h4>
    </template>
    <template #default>
      <el-form
        ref="addversionform"
        :model="add_form_data"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="版本号" prop="version">
          <el-input
            placeholder="请输入版本号"
            v-model="add_form_data.version"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="包大小(单位: M)" prop="packageSize">
          <el-input
            placeholder="请输入"
            type="number"
            v-model="add_form_data.packageSize"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="下载地址">
          <!-- <el-input
            placeholder="请输入"
            v-model="add_form_data.downloadUrl"
            show-word-limit
            maxlength="300"
          ></el-input> -->
          <upload
            :imageUrl="add_form_data.downloadUrl"
            :fileNames="['下载地址']"
            :width="100"
            :height="100"
            :uploadUrl="serviceApi.deepPlugin_version_upload"
            :limit="1"
          ></upload>
        </el-form-item>
        <el-form-item label="文件地址" prop="dllUrl">
          <upload
            :imageUrl="add_form_data.dllUrl"
            :fileNames="['文件地址']"
            :width="100"
            :height="100"
            :uploadUrl="serviceApi.deepPlugin_version_upload"
            :limit="1"
          ></upload>
        </el-form-item>
        <el-form-item label="全量包地址" prop="fullDownloadUrl">
          <upload
            :imageUrl="add_form_data.fullDownloadUrl"
            :fileNames="['全量包地址']"
            :width="100"
            :height="100"
            :uploadUrl="serviceApi.upload"
            :isCompleteUrl="false"
            :limit="1"
          ></upload>
        </el-form-item>
        <el-form-item label="强制更新">
          <el-radio v-model="add_form_data.enforce" :label="1">是</el-radio>
          <el-radio v-model="add_form_data.enforce" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="add_form_data.status" :label="1">启用</el-radio>
          <el-radio v-model="add_form_data.status" :label="2">停用</el-radio>
        </el-form-item>
        <el-form-item label="更新内容">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.content"
            type="textarea"
            show-word-limit
            maxlength="300"
          ></el-input>
        </el-form-item>
        <div class="tr m_top10">
          <el-button @click="resetForm(addversionform)">取消</el-button>
          <el-button
            type="primary"
            @click="submit(addversionform)"
            :loading="btn_loading"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  check_role,
  formatDate,
  debounce,
  handle_search_key,
} from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import upload from '@/view/components/upload.vue'
import { onMounted, ref, onUnmounted, nextTick, reactive } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { ElMessage, FormRules, ElMessageBox, FormInstance } from 'element-plus'
const has_role_list = ref([
  { path: 'version/post', has_role: false },
  { path: 'version/put', has_role: false },
])
nextTick(() => {
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
})
const attachmentUpload = (rule, value, callback) => {
  if (!add_form_data.value.dllUrl.length) {
    callback(new Error('请上传文件'))
  } else {
    callback()
  }
}
const addversionform = ref<FormInstance>()
const rules = reactive<FormRules>({
  version: [
    {
      required: true,
      message: '请输入版本号',
      trigger: 'blur',
    },
  ],
  packageSize: [
    {
      required: true,
      message: '请输入包大小',
      trigger: 'blur',
    },
  ],
  dllUrl: [
    {
      required: true,
      validator: attachmentUpload,
    },
  ],
})
const list = ref()
const total = ref()
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
})
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '版本号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '包大小',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: true,
    options: [],
  },
  {
    label: '文件地址',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '下载地址',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '全量包地址',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '强制更新',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: 1,
        label: '是',
      },
      {
        value: 2,
        label: '否',
      },
    ],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: 1,
        label: '启用',
      },
      {
        value: 2,
        label: '停用',
      },
    ],
  },
  {
    label: '创建人',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '创建时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '更新人',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '更新时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '更新内容',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 10,
  version: '',
  packageSize: '',
  dllUrl: '',
  downloadUrl: '',
  content: '',
  createByName: '',
  createTime: '',
  updateByName: '',
  updateTime: '',
  enforce: '',
  status: '',
  fullDownloadUrl: '',
})
const add_form_data = ref({
  id: '',
  version: '',
  packageSize: '',
  content: '',
  downloadUrl: [],
  enforce: 1,
  status: 1,
  fullDownloadUrl: [],
  dllUrl: [],
})
onMounted(() => {
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('操作成功！')
  })
  EventBus.on('uploadSucc', () => {
    // 上传图片成功 取消验证提示
    if (add_form_data.value.dllUrl.length) {
      addversionform.value.clearValidate(['dllUrl'])
    }
  })
  get_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const delete_list = (e) => {
  ElMessageBox.confirm('确定删除版本号为：' + e.version + ' 的记录', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.deepPlugin_version_crud + '/' + e.id,
          method: 'delete',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
    })
    .catch(() => {})
}
const edit_list = (e) => {
  add_form_data.value = {
    id: e.id,
    version: e.version,
    packageSize: e.packageSize,
    content: e.content,
    downloadUrl: e.downloadUrl ? [e.downloadUrl] : [],
    enforce: e.enforce,
    status: e.status,
    dllUrl: e.dllUrl ? [e.dllUrl] : [],
    fullDownloadUrl: e.fullDownloadUrl ? [e.fullDownloadUrl] : [],
  }
  show_box.value = true
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    console.log(valid, add_form_data.value)
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      let data = JSON.parse(JSON.stringify(add_form_data.value))
      data.dllUrl = data.dllUrl.toString()
      data.downloadUrl = data.downloadUrl.toString()
      data.fullDownloadUrl = data.fullDownloadUrl.toString()
      axios
        .request({
          url:
            data.id == ''
              ? serviceApi.deepPlugin_version_crud
              : serviceApi.deepPlugin_version_crud + '/' + data.id,
          method: data.id == '' ? 'post' : 'put',
          data: data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            show_box.value = false
            btn_loading.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.deepPlugin_version_list,
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
let list_debounce = debounce(200, get_list)
const search_key = () => {
  console.log(header_list.value)
  page_data.value = {
    current: 1,
    pageSize: 10,
    version: header_list.value[0].value,
    packageSize: header_list.value[1].value,
    dllUrl: header_list.value[2].value,
    downloadUrl: header_list.value[3].value,
    fullDownloadUrl: header_list.value[4].value,
    enforce: header_list.value[5].value,
    status: header_list.value[6].value,
    createByName: header_list.value[7].value,
    createTime: header_list.value[8].value,
    updateByName: header_list.value[9].value,
    updateTime: header_list.value[10].value,
    content: header_list.value[11].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    version: '',
    packageSize: '',
    content: '',
    downloadUrl: [],
    enforce: 1,
    status: 1,
    dllUrl: [],
    fullDownloadUrl: [],
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped></style>
